package mysql;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class TestDepEmp {
	
	private static Properties props = initProps();
	
	private static Connection conn = null;
	
	public static void main(String[] args) {
		
		String driverEspecific = getPropietat("rdbms.driver");
	
		try {
			Class.forName(driverEspecific).newInstance();
			conn = DriverManager.getConnection(getPropietat("rdbms.url"),
					getPropietat("rdbms.usuario"), getPropietat("rdbms.pwd"));
			
			String sql1 = "insert into departamento values (null,'bilbao')";
			Statement st = conn.createStatement();
			st.execute(sql1, Statement.RETURN_GENERATED_KEYS);			
			ResultSet rs = st.getGeneratedKeys();
			
			rs.next();
			int pkZar = rs.getInt(1);
			
			String sql2 = "insert into empleado values (null,'pepe', " + pkZar + ")";
			st = conn.createStatement();
			st.executeUpdate(sql2);
			
			System.out.println("Programa finalizado.");
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException e) {
			
			e.printStackTrace();
		} catch (SQLException e) {			
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {				
				e.printStackTrace();
			}
		}

		

	}
	private static Properties initProps() {

		String nomPropertiesFileDb = 
				System.getProperty("propFileDbName");

		InputStream is = TestJDBC.class.getResourceAsStream("/"
				+ nomPropertiesFileDb);

		props = new Properties();
		try {
			props.load(is);
			return props;
		} catch (IOException e) {
			e.printStackTrace();
		}
		throw new RuntimeException(
				"Error cargando fichero de propiedades de la BD!");
	}
	private static String getPropietat(String propiedad) {
		return props.getProperty(propiedad);
	}

}
